|
|
|
|
|
|
|
use RtlMoveMemory to copy data from a block of memory to a user-defined type that will allow you to easily access the data in your Visual Basic program. |
|
|
|
|
|
|
|
|
How ByVal Works (String Variables) |
|
|
|
|
|
|
|
|
Everything you have read so far relating to the ByVal statement applies to almost every type of Visual Basic variable. The one glaring exception is string variables. |
|
|
|
|
|
|
|
|
Forget the idea of ByVal meaning "by value"Visual Basic always passes pointers for string parameters. The question is, pointers to what? |
|
|
|
|
|
|
|
|
To understand what happens when you pass a string as a parameter to an API function, you must first know a bit about how Visual Basic stores strings internally and how Win32 API functions deal with string parameters. |
|
|
|
|
|
|
|
|
Visual Basic stores strings internally using objects called BSTRs. A BSTR (short for Basic STRing) is stored in memory that is managed by the operating system, specifically the OLE subsystem. This simple statement has great significance and huge consequences on the way strings are passed to API functions. |
|
|
|
|
|
|
|
|
When you assign text to a string, you know that the text must be stored somewhere in memory. When you clear a string, you can assume that the memory used by the string can be reclaimed for use by the operating system. Every program uses memory for strings and other objects, and ultimately all memory is allocated by the operating system. But you should not conclude from this that a program goes to the operating system every time it needs memory. |
|
|
|
|
|
|
|
|
It turns out that there are many different ways to manage memory, and techniques that work well to manage large blocks of memory can perform poorly when managing smaller amounts of memory. Thus it is common for different subsystems within Windows to request large blocks of memory from the operating system that are then subdivided into smaller blocks for use by that subsystem. Early versions of Visual Basic used this approach to manage string memoryVisual Basic requested a block of memory from the operating system, then used its own internal code to allocate smaller blocks for strings. As of version 4, Visual Basic switched to use the string management system built into the OLE subsystem of Windows. Strings allocated by the OLE subsystem are called BSTR strings. |
|
|
|
|
|
|
|
|
Figure T5-5 shows how a BSTR looks in memory. The first thing you'll probably notice is that the data in the string is stored as Unicode. This means that each character takes two bytes in memory. In this particular example, the string "Hello", the second byte of each character is 0; however, some character sets use both bytes. BSTR strings do not have to be in Unicode, but Visual Basic uses |
|
|
|
|
|